package middleware

import (
	"api/internal/types"
	"context"
	jwt "github.com/golangblogs/gojwt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
)

type HouseMiddleware struct {
}

func NewHouseMiddleware() *HouseMiddleware {
	return &HouseMiddleware{}
}

func (m *HouseMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO gen	erate middleware implement function, delete after code implementation
		get := r.Header.Get("token")
		if get == "" {
			resp := &types.Response{
				Code: 500,
				Msg:  "token为空",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		newJWT := jwt.NewJWT("token")
		token, err := newJWT.ParseToken(get)
		if err != nil {
			resp := &types.Response{
				Code: 500,
				Msg:  "token为空",
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, resp)
			return
		}
		value := context.WithValue(context.Background(), "userId", token.ID)
		// Passthrough to next handler if need
		next(w, r.WithContext(value))
	}
}
